/**
 * Created by wenquxing on 2016/5/26.
 */
var cluster = require('cluster');
var os = require('os');
// 获取CPU 的数量
var numCPUs = os.cpus().length;

var workers = {};
if(cluster.isMaster){
    // 主进程分支
    cluster.on('death',function (worker) {
        // 当一个工作进程结束时,重启工作进程
        delete workers[worker.pid];
        worker = cluster.fork();
        workers[worker.pid] = worker;

    });

    // 初始开启与cpu数量相同的工作进程
    for (var i = 0 ;i<numCPUs;i++){
        var worker = cluster.fork();
        workers[worker.pid] = worker;
    }
}
else {
    //工作进程分支,启动服务器
    var app = require('./app');
    app.listen(3000);
}


// 检查进程是否是 master 进程
/*if (cluster.isMaster) {
    for (var i = 0; i < numCPUs; ++i)
        // 生成新的 worker 进程（只有 master 进程才可以调用）
        cluster.fork();

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    var app = require('./app');
    app.listen(3000);
}*/

// 当主进程被终止时,关闭所有工作进程
process.on('SIGTERE',function () {
    for(var pid in workers){
        process.kill(pid);
    }

    process.exit(0);
})